package com.echat.api.demo.servlet;

import com.echat.api.demo.info.User;
import com.echat.api.demo.info.bizdata.*;
import com.echat.api.demo.util.EChatAPIConfig;
import com.echat.api.demo.util.EChatAPIUtil;
import com.echat.api.demo.util.StringUtil;
import com.echat.api.demo.util.XMLUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by EChat
 * 集成到一洽的业务系统
 * 1.将此页面的URL配置到一洽的API接口中（添加业务系统）
 * 2.添加后会在客服端聊天界面的右侧展示
 * 3.切换访客时会刷新此页面，将数据传递给此页面
 */
public class MyBusinessPage extends HttpServlet {

    /**
     * @param req
     * @param resp
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException            一洽通过get参数将签名和业务数据发送到客户的业务系统页面
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String nonce = req.getParameter("nonce");
        String timeStamp = req.getParameter("timestamp");
        req.setCharacterEncoding("utf-8");
        if (StringUtil.isNotEmpty(signature) && StringUtil.isNotEmpty(nonce) && StringUtil.isNotEmpty(timeStamp)) {
            try {
                boolean verify = EChatAPIUtil.verifyURL(nonce, timeStamp, signature);
                if (verify) {
                    resp.setCharacterEncoding("utf-8");
                    PrintWriter writer = resp.getWriter();
                    writeStyle(writer);
                    writer.println("<table>");
                    writer.println("<tr><th>参数名</th><th>GET参数</th><th>参数解析</th>");
                    writeSimple(writer, "signature", signature);
                    writeSimple(writer, "nonce", nonce);
                    writeSimple(writer, "timeStamp", timeStamp);

                    //对话状态
                    String chatStatus = req.getParameter("chatStatus");
                    writeSimple(writer, "chatStatus", chatStatus);
                    //登录客服
                    String logData = req.getParameter("logData");
                    writeComplex(writer, "logData", logData);
                    //会员数据
                    String metadata = req.getParameter("metaData");
                    User user = EChatAPIUtil.getUserFromMetaData(metadata);
                    if (user != null) {
                        String userStr = XMLUtil.toXML(user);
                        userStr = userStr.replaceAll("<", "&lt");
                        userStr = userStr.replaceAll(">", "&gt");
                        writeSimple(writer, "metadata", userStr);
                    }

                    //开发者自定义扩展数据
                    String myData = req.getParameter("myData");
                    writeComplex(writer, "myData", myData);
                    //访客数据
                    String visitorData = req.getParameter("visitorData");
                    writeComplex(writer, "visitorData", visitorData);
                    //路由数据
                    String routeData = req.getParameter("routeData");
                    writeComplex(writer, "routeData", routeData);
                    //对话数据
                    String chatData = req.getParameter("chatData");
                    writeComplex(writer, "chatData", chatData);
                    //客户数据
                    String crmData = req.getParameter("crmData");
                    writeComplex(writer, "crmData", crmData);
                    writer.println("</table>");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //获取一洽传递给客户的业务数据
        //1.如果需要判定用户的会员身份，则通过metaData信息获取会员身份
    }

    /**
     * 将整体的数据解析为map的形式
     *
     * @param str
     * @return
     */
    private Map<String, String> parseParam(String str) {
        if (str != null && str.contains("&")) {
            Map<String, String> params = new LinkedHashMap<String, String>();
            String[] pairs = str.split("&");
            for (String pair : pairs) {
                if (pair != null && pair.contains("=")) {
                    String[] param = pair.split("=");
                    String paramKey = param[0];
                    String paramValue = "null";
                    if (param.length == 2) {
                        paramValue = param[1];
                    }
                    params.put(paramKey, paramValue);
                }
            }
            return params;
        }
        return null;
    }

    /**
     * 打印单独的参数
     *
     * @param writer
     * @param name
     * @param value
     */
    private void writeSimple(PrintWriter writer, String name, String value) {
        writer.println("<tr>");
        writer.println("<td>" + name + "</td>");
        writer.println("<td>" + name + " = " + value + "</td>");
        writer.println("<td>" + name + " : " + value + "</td>");
        writer.println("</tr>");
    }

    /**
     * 打印复杂类型的参数
     *
     * @param writer
     * @param name
     * @param value
     */
    private void writeComplex(PrintWriter writer, String name, String value) {
        Map<String, String> params = parseParam(value);
        writer.println("<tr>");
        writer.println("<td>" + name + "</td>");
        writer.println("<td>" + name + " = " + value + "</td>");

        writer.println("<td>");
        if (params != null) {
            Set entrySet = params.entrySet();
            Iterator iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                writer.print(entry.getKey() + " : " + entry.getValue() + "<br>");
            }
        } else {
            writer.print(name + " : null");
        }
        writer.println("</td>");
        writer.println("</tr>");
    }

    private void writeStyle(PrintWriter writer) {
        writer.println("<style>" +
                "td{" +
                "border:1px solid black;" +
                "}" +
                "" +
                "" +
                "</style>");
    }
}
